﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Data;
using System.Web.UI.WebControls;
using weikebuluo.Model;
using weikebuluo.DAL;

namespace weikeweixin.web.admin.wechat
{
    public partial class bindapi : weikeweixin.web.admin.cs.adminbase
    {
        w_wechat_dal wechatdal = new w_wechat_dal();

        protected w_wechat_model wechatmodel = new w_wechat_model();
        protected DataTable dtweixin = new DataTable();

        protected void Page_Load(object sender, EventArgs e)
        {
            dtweixin = wechatdal.GetList(" user_id =" + user_id).Tables[0];

            if (dtweixin.Rows.Count <= 0)
            {
                string weixin_key = Guid.NewGuid().ToString();
                string weixin_url = "http://" + Request.Url.Authority + "/web/wechat/api/wechatapi.aspx?key=" + weixin_key;
                wechatmodel.wechat_token = GetRandom();
                wechatmodel.wechat_url = weixin_url;
                wechatmodel.wechat_key = weixin_key;
                wechatmodel.wechat_addtime = DateTime.Now;
                wechatmodel.user_id = int.Parse(user_id);
                wechatdal.Add(wechatmodel);
            }
            else
            {
                wechatmodel = wechatdal.GetModel(int.Parse(dtweixin.Rows[0]["wechat_id"].ToString()));
            }
            switch (Request.Form["action"])
            {
                case "bindapi":
                    api();
                    break;
            }
        }

        private void api()
        {
            dtweixin = wechatdal.GetList(" user_id =" + user_id).Tables[0];
            if (dtweixin.Rows.Count > 0)
            {
                wechatmodel = wechatdal.GetModel(int.Parse(dtweixin.Rows[0]["WeChat_ID"].ToString()));
                wechatmodel.wechat_url = Request.Form["name"].Trim().ToString();
                wechatmodel.wechat_name = Request.Form["weixin_name"].Trim().ToString();
                wechatmodel.wechat_appid = Request.Form["appid"].Trim().ToString();
                wechatmodel.wechat_appsecret = Request.Form["appsecret"].Trim().ToString();
                wechatmodel.wechat_originalid = Request.Form["originalid"].Trim().ToString();
                wechatmodel.wechat_type = int.Parse(Request.Form["is_show"].Trim().ToString());
                wechatdal.Update(wechatmodel);
                Response.Write("{\"errno\":\"0\",\"tip\":\"设置成功！\",\"url\":\"bindapi.aspx\",\"error\":\"\"}");
            }
            Response.End();
        }
        #region 获取10位随即数(字符串类型)
        /// <summary>
        /// 获取10位随即数(字符串类型)
        /// </summary>
        /// <returns></returns>
        private string GetRandom()
        {
            Random ran = new Random();
            int RandomValue = ran.Next(999999999) + 1000000000;
            return RandomValue.ToString();
        }
        #endregion 获取10位随即数(字符串类型)

    }
}